import React, { useEffect, useMemo, useRef, useState } from 'react'
import { Input, Button ,NavBar} from 'antd-mobile'
import { useNavigate } from 'react-router-dom'
import styles from './index.module.css'
function Message() {
let navtion=useNavigate()
  let user_id = 1
  let server_id = 1234
  let mesper = useRef()
  let [messlist, setMesslist] = useState([])
  const [message, setMessage] = useState('')
  const ws = useMemo(() => {
    return new WebSocket(
      `ws:113.44.139.133:8003/koa/ws?user_id=${user_id}&server_id=${server_id}`
    )
  }, [])

  useEffect(() => {
    ws.onopen = (() => {
      console.log('连接成功');
      ws.send(JSON.stringify({ type: 'getChatList' }))
    })
    ws.onmessage = ((msg) => {
      let { data, type } = JSON.parse(msg.data)
      if (type == 'getChatList') {
        setMesslist(data)
        console.log(data);

      }
      else {
        setMesslist((per) => [...per, data])
      }
    })
  }, [])

  const dj = () => {
    if (message.trim()== '') 
       return Toast.show({
        icon: "fail",
        content: "请输入内容！",
        duration: 1000,
      });

      ws.send(JSON.stringify({
        type: 'addMessage',
        data: {
          user_id,
          server_id,
          message
        }
      }))
      setMessage('')
    
  }

  useEffect(() => {
    if (mesper.current) {
      mesper.current.scrollTop == 1000000000
    }

  }, [messlist])
  return (
    <div className={styles.cook}>
    <NavBar onBack={()=>navtion(-1)}>标题</NavBar>
      <div className={styles.main}>
     {
        messlist.length > 0 && messlist.map((item, index) => (
          <dl key={index} ref={mesper}>
            <dt> <img src={item.user_avatar} width={50} height={50} /> </dt>
            <dd>{item.message}</dd>
          </dl>
        ))
      }
      </div>
 
      <div className={styles.footer}>
        <Input
          placeholder='请输入内容'
          value={message}
          onChange={val => {
            setMessage(val)
          }}
        />
        <Button color='primary' fill='solid' onClick={() => dj()} disabled={!message}>
          Solid
        </Button>
      </div>
    </div>
  )
}

export default Message
